import React, { useEffect, useState } from 'react';
import { Table, Card, Tag, Empty, Alert } from 'antd';

const ProductRankPage = () => {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchRank = async () => {
      setLoading(true);
      setError(null);
      try {
        const res = await fetch('http://localhost:3001/api/products/rank');
        if (!res.ok) throw new Error('网络错误');
        const data = await res.json();
        setProducts(Array.isArray(data) ? data : []);
      } catch (err) {
        setError('获取数据失败，请检查后端服务和数据库');
        setProducts([]);
      } finally {
        setLoading(false);
      }
    };
    fetchRank();
  }, []);

  const columns = [
    { title: '排名', dataIndex: 'rank', key: 'rank', render: (_, __, idx) => idx + 1 },
    { title: '商品名称', dataIndex: 'name', key: 'name' },
    { title: '分类', dataIndex: 'category', key: 'category' },
    { title: '单价', dataIndex: 'price', key: 'price', render: v => `¥${v}` },
    { title: '库存', dataIndex: 'stock', key: 'stock' },
    { title: '今日销量', dataIndex: 'todaySales', key: 'todaySales', render: v => <Tag color="green">{v}</Tag> }
  ];

  return (
    <Card title="商品销量排行榜">
      {error && <Alert type="error" message={error} showIcon style={{ marginBottom: 16 }} />}
      <Table
        columns={columns}
        dataSource={products}
        rowKey={record => record._id || record.name}
        loading={loading}
        locale={{ emptyText: <Empty description="暂无数据" /> }}
        pagination={{ pageSize: 10 }}
      />
    </Card>
  );
};

export default ProductRankPage; 